import requests
from utils.http import get_request_headers
from settings import TEST_TIMEOUT
import time
import json
from domain import Proxy
# from utils.log import logger


def checks(proxies, test_url):
    is_connected = False
    speed = -1
    nick_type = -1
    start = time.time()
    try:
        response = requests.get(url=test_url, headers=get_request_headers(), proxies=proxies, timeout=TEST_TIMEOUT)
        if response.ok:
            is_connected = True
            speed = round(time.time()-start, 2)
            content = response.text
            content_dic = json.loads(content)
            origin = content_dic['origin']
            headers = content_dic['headers']
            if ',' in origin:
                nick_type = 2
            elif headers.get('Proxy-Connection', None):
                nick_type = 1
            else:
                nick_type = 0
            return is_connected, speed, nick_type
        return is_connected, speed, nick_type
    except Exception:
        return is_connected, -1, nick_type


def check_proxy(proxy):
    # 将ip对象组装成链接
    http_proxy = f'http://{proxy.ip}:{proxy.port}'
    https_proxy = f'https://{proxy.ip}:{proxy.port}'

    proxies = {
        'http': http_proxy,
        'https': https_proxy
    }

    http_is_connected, http_speed, http_nick_type = checks(proxies, 'http://httpbin.org/get')
    https_is_connected, https_speed, https_nick_type = checks(proxies, 'https://httpbin.org/get')

    # 根据返回的值更新ip对象的属性
    if http_is_connected and https_is_connected:
        proxy.protocol = 2
        proxy.speed = https_speed
        proxy.nick_type = https_nick_type
    elif https_is_connected:
        proxy.protocol = 1
        proxy.speed = https_speed
        proxy.nick_type = https_nick_type
    elif http_is_connected:
        proxy.protocol = 0
        proxy.speed = http_speed
        proxy.nick_type = http_nick_type
    else:
        proxy.protocol = -1
        proxy.speed = -1
        proxy.nick_type = -1
    return proxy


if __name__ == '__main__':
    pproxy = Proxy(ip='118.190.244.234', port='3128')
    pproxy = check_proxy(pproxy)
    print(pproxy)
